<script setup lang="ts">
definePageConfig({
  navigationBarTitleText: '健康码验证'
});

import { ref, reactive, onMounted, watch } from 'vue';
// import { useRouter } from 'vue-router';
import { useToast } from '@/composables';
import { verifyHealthCode } from '@/service/api/auth';

// const router = useRouter();
const toast = useToast();

const form = reactive({
  name: '', // 姓名
  idCard: '', // 身份证号
  healthCodeType: 'green', // 健康码类型：green-绿码，yellow-黄码，red-红码
  temperature: '', // 体温
  date: '', // 日期
  location: '', // 地区
  codeImage: '' // 健康码图片
});

const rules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证格式不正确', trigger: 'blur' }
  ],
  temperature: [
    { required: true, message: '请输入体温', trigger: 'blur' },
    { pattern: /^\d{1,2}(\.\d)?$/, message: '体温格式不正确', trigger: 'blur' },
    { validator: (rule: any, value: string) => {
        const temp = parseFloat(value);
        return temp >= 35 && temp <= 42;
      }, message: '体温范围应为35-42℃', trigger: 'blur' }
  ],
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请选择地区', trigger: 'change' }
  ],
  codeImage: [
    { required: true, message: '请上传健康码截图', trigger: 'change' }
  ]
});

const formRef = ref(null);
const isLoading = ref(false);
const isUploading = ref(false);
const uploadPercent = ref(0);

// 健康码类型选项
const healthCodeOptions = [
  { label: '绿码', value: 'green' },
  { label: '黄码', value: 'yellow' },
  { label: '红码', value: 'red' }
];

// 今日日期
onMounted(() => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  form.date = `${year}-${month}-${day}`;
});

// 上传健康码图片
const uploadHealthCodeImage = () => {
  // 实际项目中应调用文件上传API
  // 这里使用模拟上传过程
  isUploading = true;
  uploadPercent.value = 0;
  
  const timer = setInterval(() => {
    uploadPercent.value += 10;
    
    if (uploadPercent.value >= 100) {
      clearInterval(timer);
      isUploading = false;
      
      // 模拟上传成功，生成随机图片URL
    //   const randomId = Math.floor(Math.random() * 1000);
    //   form.codeImage = `https://picsum.photos/400/600?random=${randomId}`;
    //   toast.success('上传成功');
    }
  }, 200);
};

// 提交验证
const submitVerification = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate().then(async () => {
    try {
      isLoading.value = true;
      toast.loading('验证中...');
      
      // 调用健康码验证API
      const res = await verifyHealthCode({
        name: form.name,
        idCard: form.idCard,
        healthCodeType: form.healthCodeType,
        temperature: parseFloat(form.temperature),
        date: form.date,
        location: form.location,
        codeImage: form.codeImage
      });
      
      if (res.code === 0) {
        toast.success('健康码验证成功');
        // 延迟后返回上一页
        setTimeout(() => {
        //   router.back();
        }, 1500);
      } else {
        toast.error(res.message || '健康码验证失败');
      }
    } catch (error: any) {
      toast.error(error.message || '健康码验证失败，请稍后再试');
    } finally {
      isLoading.value = false;
    }
  }).catch(err => {
    // 表单验证失败
  });
};

// 格式化身份证号
const formatIdCard = (idCard: string) => {
  if (!idCard) return '';
  return idCard.replace(/(\d{6})(\d{8})(\d{4})/, '$1********$3');
};
</script>

<template>
  <basic-layout>
    <view class="bg-white min-h-screen p-4">
      <!-- 提示信息 -->
      <view class="bg-blue-50 border-l-4 border-blue-400 p-4 rounded-r my-4">
        <view class="flex items-start">
          <view class="i-local-info-circle text-blue-500 mt-0.5"></view>
          <view class="ml-2 text-sm text-blue-700">
            请上传近期健康码截图进行验证，确保信息真实有效
          </view>
        </view>
      </view>
      
      <!-- 表单 -->
      <nut-form ref="formRef" :rules="rules">
        <nut-form-item label="姓名" prop="name">
          <nut-input 
            v-model="form.name" 
            placeholder="请输入姓名"
          />
        </nut-form-item>
        
        <nut-form-item label="身份证号" prop="idCard">
          <nut-input 
            v-model="form.idCard" 
            placeholder="请输入身份证号"
            type="idcard"
          />
        </nut-form-item>
        
        <nut-form-item label="健康码颜色" prop="healthCodeType">
          <nut-picker 
            v-model="form.healthCodeType" 
            :columns="healthCodeOptions"
            :show-toolbar="false"
            @confirm="(value) => form.healthCodeType = value"
          >
            <template #content>
              <view class="flex items-center justify-between h-10 px-3 border border-gray-200 rounded">
                <text>{{ healthCodeOptions.find(item => item.value === form.healthCodeType)?.label || '请选择' }}</text>
                <view class="i-local-arrow-down text-gray-400"></view>
              </view>
            </template>
          </nut-picker>
        </nut-form-item>
        
        <nut-form-item label="体温(℃)" prop="temperature">
          <nut-input 
            v-model="form.temperature" 
            placeholder="请输入体温"
            type="digit"
          />
        </nut-form-item>
        
        <nut-form-item label="日期" prop="date">
          <!-- <nut-datetime-picker
            v-model="form.date"
            type="date"
            :show-toolbar="false"
            @confirm="(value) => form.date = value"
          >
            <template #content>
              <view class="flex items-center justify-between h-10 px-3 border border-gray-200 rounded">
                <text>{{ form.date || '请选择日期' }}</text>
                <view class="i-local-arrow-down text-gray-400"></view>
              </view>
            </template>
          </nut-datetime-picker> -->
        </nut-form-item>
        
        <nut-form-item label="地区" prop="location">
          <!-- <nut-area 
            v-model="form.location"
            :show-toolbar="false"
            @confirm="(value) => form.location = value"
          >
            <template #content>
              <view class="flex items-center justify-between h-10 px-3 border border-gray-200 rounded">
                <text>{{ form.location || '请选择地区' }}</text>
                <view class="i-local-arrow-down text-gray-400"></view>
              </view>
            </template>
          </nut-area> -->
          <view>123</view>
        </nut-form-item>
        
        <nut-form-item label="健康码截图" prop="codeImage">
          <view class="flex flex-col">
            <view 
              v-if="form.codeImage" 
              class="w-full h-48 bg-gray-100 rounded-lg overflow-hidden mb-2"
            >
              <image 
                :src="form.codeImage" 
                mode="aspectFill" 
                class="w-full h-full"
                alt="健康码图片"
              />
            </view>
            
            <nut-button 
              :type="form.codeImage ? 'default' : 'primary'" 
              :loading="isUploading"
              @click="uploadHealthCodeImage"
            >
              {{ form.codeImage ? '重新上传' : '上传健康码截图' }}
            </nut-button>
            
            <view v-if="isUploading" class="w-full bg-gray-200 rounded-full h-2 mt-2">
              <view class="bg-blue-600 h-2 rounded-full" :style="{ width: `${uploadPercent}%` }"></view>
            </view>
          </view>
        </nut-form-item>
        
        <!-- 确认按钮 -->
        <view class="mt-6">
          <nut-button 
            type="primary" 
            size="large" 
            @click="submitVerification"
            :loading="isLoading"
            class="w-full"
          >
            确认提交
          </nut-button>
        </view>
      </nut-form>
      
      <!-- 隐私政策 -->
      <view class="mt-4 text-center text-xs text-gray-500">
        <text>点击"确认提交"，即表示您同意</text>
        <text class="text-blue-500">《健康信息服务条款》</text>
        <text>和</text>
        <text class="text-blue-500">《隐私政策》</text>
      </view>
    </view>
  </basic-layout>
</template>  